from django.shortcuts import render, redirect
from django.http import HttpResponse

from comment.models import Comment
from .models import ArticlePost,ArticleColumn
from .forms import ArticlePostForm
from django.contrib.auth.models import User
import markdown
from django.core.paginator import Paginator
from django.db.models import Q


# Create your views here.
def article_list(request):
    '''
    文章列表
    :param request:
    :return:
    '''
    search = request.GET.get('search')
    order = request.GET.get('order')
    # 用户搜索逻辑
    if search:
        if request.GET.get('order') == 'total_view':
            article_list = ArticlePost.objects.filter(Q(title__icontains=search) | Q(body__icontains=search)).order_by(
                '-total_view')
        else:
            article_list = ArticlePost.objects.filter(Q(title__icontains=search) | Q(title__icontains=search))
    else:
        search = ''
        if order == 'total_view':
            article_list = ArticlePost.objects.all().order_by('-total_view')
        else:
            article_list = ArticlePost.objects.all()
    paginator = Paginator(article_list, 3)
    page = request.GET.get('page')
    articles = paginator.get_page(page)
    context = {'articles': articles, 'order': order, 'search': search}
    return render(request, 'article/list.html', context)


def article_detail(request, id):
    '''
    文章详情
    :param request:
    :param id:
    :return:
    '''
    article = ArticlePost.objects.get(id=id)
    comments = Comment.objects.filter(article=id)
    article.total_view += 1
    article.save(update_fields=['total_view'])
    article.body = markdown.markdown(article.body,
                                     extensions=['markdown.extensions.extra', 'markdown.extensions.codehilite',
                                                 'markdown.extensions.toc'])
    context = {'article': article, 'comments': comments}
    return render(request, 'article/detail.html', context)


def article_create(request, id):
    '''
    创建文章
    :param request:
    :return:
    '''
    if request.method == 'POST':
        article_post_form = ArticlePostForm(request.POST,request.FILES)
        if article_post_form.is_valid():
            new_article = article_post_form.save(commit=False)
            new_article.author = User.objects.get(id=id)
            if request.POST['column'] != 'none':
                new_article.column = ArticleColumn.objects.get(id=request.POST['column'])
            new_article.save()
            return redirect('article:article_list')
        else:
            return HttpResponse('表单内容有误，请重新填写。')
    else:
        article_post_form = ArticlePostForm()
        columns = ArticleColumn.objects.all()
        context = {'article_post_form': article_post_form,'columns':columns}
        return render(request, 'article/create.html', context)


def article_delete(request, id):
    '''
    删除文章
    :param request:
    :param id:
    :return:
    '''
    article = ArticlePost.objects.get(id=id)
    if request.user != article.author:
        return HttpResponse("抱歉，你不是该文章的主人")
    else:
        article.delete()
        return redirect('article:article_list')


def article_update(request, id):
    '''
    修改文章
    :param request:
    :return:
    '''
    article = ArticlePost.objects.get(id=id)
    if request.user != article.author:
        return HttpResponse("抱歉，你不是该文章的主人")
    else:
        if request.method == "POST":
            article_post_form = ArticlePostForm(data=request.POST)
            if article_post_form.is_valid():
                article.title = request.POST['title']
                if request.POST['column'] != 'none':
                    article.column = ArticleColumn.objects.get(id=request.POST['column'])
                else:
                    article.column = None
                article.body = request.POST['body']
                article.save()
                return redirect('article:article_detail', id=id)
            else:
                return HttpResponse('表单内容有误，请重新填写。')
        else:
            article_post_from = ArticlePostForm()
            columns = ArticleColumn.objects.all()
            context = {'article': article, 'article_post_form': article_post_from,'columns':columns}
            return render(request, 'article/update.html', context)
